package pers.mihao.quickstream.publish.repository.impl;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.support.TransactionTemplate;
import pers.mihao.quickstream.common.exception.BaseException;
import pers.mihao.quickstream.publish.model.convertor.PublishTaskConvertor;
import pers.mihao.quickstream.publish.model.dto.PublishTaskDTO;
import pers.mihao.quickstream.publish.repository.PublishTaskRepository;
import pers.mihao.quickstream.publish.repository.domain.PublishTaskDO;
import pers.mihao.quickstream.publish.repository.mapper.PublishTaskMapper;

import javax.annotation.Resource;

/**
 * @author mihao
 * @since 2024/11/22
 */
@Repository
public class PublishTaskRepositoryImpl implements PublishTaskRepository {

    @Resource
    PublishTaskMapper publishTaskMapper;

    @Resource
    TransactionTemplate transactionTemplate;

    @Resource
    PublishTaskConvertor publishTaskConvertor;

    @Override
    public void create(PublishTaskDTO publishTaskDTO) {
        PublishTaskDO publishTaskDO = publishTaskConvertor
                .map2PublishTaskDO(publishTaskDTO);
        transactionTemplate.execute(c -> {
            int insert = publishTaskMapper.insert(publishTaskDO);
            if (insert != 1) {
                c.setRollbackOnly();
                throw new BaseException();
            }
            publishTaskDTO.setId(publishTaskDO.getId());
            publishTaskDTO.setGmtCreate(publishTaskDO.getGmtCreate());
            publishTaskDTO.setGmtModify(publishTaskDO.getGmtModify());
            return c;
        });
    }

    @Override
    public PublishTaskDTO queryById(Long taskId) {
        PublishTaskDO publishTaskDO = publishTaskMapper.selectById(taskId);
        return publishTaskConvertor.map2PublishTaskDTO(publishTaskDO);
    }

    @Override
    public void update(PublishTaskDTO publishTaskDTO) {
        PublishTaskDO publishTaskDO = publishTaskConvertor.map2PublishTaskDO(publishTaskDTO);
        transactionTemplate.execute(c -> {
            int insert = publishTaskMapper.updateByIdWithVersion(publishTaskDO);
            if (insert != 1) {
                c.setRollbackOnly();
                throw new BaseException();
            }
            return c;
        });
    }


}
